package cn.tedu.v5;
//127.0.0.1

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class Client {
private Socket socket;
String ip;
private  static final String HOST="127.0.0.1";
private  static final Integer PORT=5588;
private BufferedReader br;
private PrintWriter pw;

public Client() {
try {

socket=new Socket(HOST,PORT);
br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8"));
pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);

}catch (NullPointerException e){
System.out.println("友情提示：IP传入错误导致链接失败");
} catch (UnknownHostException e){
System.out.println("友情提示：IP传入错误");
} catch (ConnectException e){
System.out.println("客户端链接服务器端失败，提示：检查IP/端口");
} catch (IOException e) {
System.out.println("客户端链接服务器端失败，提示：检查IP/端口");
}
ip=socket.getInetAddress().getHostAddress();
}
//封装一个聊天功能：读写Chat()
private void chat() {
new Thread(()->{
try {
String message;
while((message= br.readLine())!=null){
System.out.println(message);
System.out.println("客户端请输入：");
}
} catch (IOException e) {
System.out.println("服务器端读入失败");
}
}).start();
Scanner input=new Scanner(System.in);

while(true){
System.out.println("客户端请输入：");
//String ip=socket.getInetAddress().getHostAddress();
String line=input.nextLine();//发给服务器
pw.println(ip+"客户端说"+line);
//System.out.println(ip+"恭喜你抽中五百万！" );
}
}
public void start()  {
//与服务器端交互 参考：Server服务器端
System.out.println("----欢迎使用超咪牌QQ聊天室----");
Scanner input=new Scanner(System.in);
try {
//1.读入服务器端："请输入用户名"
String serverMessage=br.readLine();
//1.1显示“请输入用户名：”
System.out.println(serverMessage);
//1.2  写出用户名
String username=input.nextLine();
//1.3用户输入的用户名--写出给服务器端
 pw.println(username);
 //2.1 服务器端写出："请输入密码"
 serverMessage= br.readLine();
    System.out.println(serverMessage);
    //2.2用户输入---密码---写出给服务器端
String password=input.nextLine();
pw.println(password);
//3.登录之后【登录成功，登录失败】--才可以聊天
serverMessage=br.readLine();//读入【登录成功，登录失败】
//字符串方法：startWith()  返回值 boolean 前缀名称一般true
if (serverMessage.startsWith("登陆成功")) {
//
chat();
}else{
 pw.println("登陆失败，用户名或者密码错误");
 socket.close();
}
} catch (IOException e) {
System.out.println("客户端断开链接");
}catch (NullPointerException e) {
System.out.println("IO流传入对象，有对象为null，立马核对，建议：查看try块中对象可能赋值为null");
}
finally {
    if (br != null)
        try {
            br.close();
        } catch (IOException e) {
            System.out.println("结束通讯，通讯关闭");
        }
    if (pw != null)
        pw.close();
    if (socket != null && !socket.isClosed())
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}}
public static void main(String[] args) {
new Client().start();
}
}
